package tk.mybatis.mapper.custom.select.provider;

import org.apache.ibatis.mapping.MappedStatement;
import tk.mybatis.mapper.MapperException;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;
import tk.mybatis.mapper.mapperhelper.SqlHelper;

import java.util.Set;

public class CustomSelectProvider extends MapperTemplate {
    public CustomSelectProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }

    public String selectByPrimaryKeyList(MappedStatement ms) {
        final Class<?> entityClass = getEntityClass(ms);
        //修改返回值类型为实体类型
        setResultType(ms, entityClass);
        StringBuilder sql = new StringBuilder();
        sql.append(SqlHelper.selectAllColumns(entityClass));
        sql.append(SqlHelper.fromTable(entityClass, tableName(entityClass)));

        Set<EntityColumn> pkColumns = EntityHelper.getPKColumns(entityClass);
        if (pkColumns.size() == 1) {
            EntityColumn column = pkColumns.iterator().next();
            sql.append("<foreach collection=\"list\" item=\"item\" open=\"where ").append(column.getColumn()).append(" IN (\" close=\")\" separator=\",\">#{item}</foreach>");
        } else {
            throw new MapperException("继承 selectByPrimaryKeyList 方法的实体类[" + entityClass.getName() + "]中必须只有一个带有 @Id 注解的字段");
        }
        return sql.toString();
    }
}
